package medium.slidewindow;

/**
 * <a href="https://leetcode-cn.com/problems/grumpy-bookstore-owner">1052. 爱生气的书店老板</a>
 * 今天，书店老板有一家店打算试营业customers.length分钟。每分钟都有一些顾客（customers[i]）会进入书店，所有这些顾客都会在那一分钟结束后离开。
 * 在某些时候，书店老板会生气。 如果书店老板在第 i 分钟生气，那么 grumpy[i] = 1，否则 grumpy[i] = 0。 当书店老板生气时，那一分钟的顾客就会不满意，不生气则他们是满意的。
 * 书店老板知道一个秘密技巧，能抑制自己的情绪，可以让自己连续X分钟不生气，但却只能使用一次。
 * 请你返回这一天营业下来，最多有多少客户能够感到满意的数量。
 * 示例：
 *   输入：customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
 *   输出：16
 *   解释：书店老板在最后 3 分钟保持冷静。感到满意的最大客户数量 = 1 + 1 + 1 + 1 + 7 + 5 = 16.
 * 提示：
 *   1 <= X <= customers.length == grumpy.length <= 20000
 *   0 <= customers[i] <= 1000
 *   0 <= grumpy[i] <= 1
 * @author 刘学松
 * @date 2021/2/23 19:08
 */
public class 爱生气的书店老板 {
    public static void main(String[] args) {
        int[] custmoers = {1,0,1,2,1,1,7,5};
        int[] grupy = {0,1,0,1,0,1,0,1};
        int x = 3;
        System.out.println(maxSatisfied(custmoers, grupy, x));
    }

    public static int maxSatisfied(int[] customers, int[] grumpy, int x) {
        int length = customers.length;
        int slideCount = 0;
        int leftCount = 0;
        int rightCount = 0;
        for (int i = 0; i < x; i++) {
            slideCount += customers[i];
        }
        for (int i = x; i < length; i++) {
            if (grumpy[i] == 0) {
                rightCount += customers[i];
            }
        }

        int maxCount = slideCount + rightCount;

        for (int i = x; i < length; i++) {
            if (grumpy[i] == 0) {
                rightCount -= customers[i];
            }
            if (grumpy[i - x] == 0) {
                leftCount += customers[i-x];
            }
            slideCount += customers[i] - customers[i-x];
            maxCount = Math.max(maxCount, leftCount + slideCount + rightCount);
        }

        return maxCount;
    }

    /**
     * 最优解
     * @param customers
     * @param grumpy
     * @param x
     * @return
     */
    public static int maxSatisfied1(int[] customers, int[] grumpy, int x) {
        int total = 0;
        int n = customers.length;
        for (int i = 0; i < n; i++) {
            if (grumpy[i] == 0) {
                total += customers[i];
            }
        }
        int increase = 0;
        for (int i = 0; i < x; i++) {
            increase += customers[i] * grumpy[i];
        }
        int maxIncrease = increase;
        for (int i = x; i < n; i++) {
            increase = increase - customers[i - x] * grumpy[i - x] + customers[i] * grumpy[i];
            maxIncrease = Math.max(maxIncrease, increase);
        }
        return total + maxIncrease;
    }
}
